<template>
  <div class="app-container">
    <div class="app-container-inner">
      <div v-if="userStore.utype == 2">
        <div class="mt-4" style="margin-bottom: 3%">
          <el-input
            v-model="period"
            placeholder="输入入党阶段"
            class="input-with-select"
            @input="searchByPeriod"
          >
            <template #prepend> 搜索 </template>
            <template #append>
              <el-button :icon="Search" />
            </template>
          </el-input>
        </div>
        <div class="mt-4" style="margin-bottom: 3%">
          <el-input
            v-model="name"
            placeholder="输入党员名称"
            class="input-with-select"
            @input="searchByName"
          >
            <template #prepend> 搜索 </template>
            <template #append>
              <el-button :icon="Search" />
            </template>
          </el-input>
        </div>
        <el-table :data="tableData" border style="width: 100%" fit class="table" show-header>
          <el-table-column v-if="false" prop="_id" label="id" width="200" align="center" />
          <el-table-column prop="upload_date" label="上传时间" width="200" align="center" />
          <el-table-column prop="name" label="入党阶段" width="200" align="center" />
          <el-table-column prop="personName" label="党员名称" align="center"> </el-table-column>
          <el-table-column prop="content" label="查看信息" align="center">
            <template #default="scoped">
              <el-button link type="primary" size="small" @click="download(scoped.row._id)"
                >下载党员上传文件</el-button
              >
              <el-button link type="primary" size="small" @click="showMessage(scoped.row._id)"
                >查看党员发送信息</el-button
              >
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template #default="scoped">
              <el-button
                v-if="scoped.row.status == '审核中'"
                link
                type="primary"
                size="small"
                @click="check(scoped.row._id)"
                >通过</el-button
              >
              <el-button
                v-if="scoped.row.status == '审核中'"
                link
                type="primary"
                size="small"
                @click="failCheck(scoped.row._id)"
                >不通过</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="status" label="审核结果" align="center"> </el-table-column>
        </el-table>
        <div>
          <el-dialog v-model="Visible" title="文件预审信息书写" width="80%">
            <Wangeditor v-model="editorContent" style="margin-bottom: 2%"></Wangeditor>
            <el-button type="primary" @click="send">发送</el-button>
            <el-button @click="Visible = false">取消</el-button>
          </el-dialog>
        </div>
        <div>
          <el-dialog v-model="messageVisible" title="党员发送的信息" width="30%" center>
            <div v-html="message"></div>
            <template #footer>
              <span class="dialog-footer">
                <el-button type="success" @click="messageVisible = false"> 确定 </el-button>
              </span>
            </template>
          </el-dialog>
        </div>
        <el-pagination
          background
          layout="prev, pager, next"
          style="margin-left: 65%; margin-top: 2%"
          small
          :total="total"
          @current-change="handelCurrentChange"
          v-model:current-page="currentPage"
        />
      </div>
      <div v-else>
        <Error></Error>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { onMounted, ref, onUnmounted } from 'vue'
  import { Search } from '@element-plus/icons-vue'
  import Wangeditor from '../../components/WangEdior/index.vue'
  import { getApproval, getApplyInfo } from '@/lafSdkCollection/getApplyInfo'
  import { getMemberName } from '@/lafSdkCollection/getPartyMember'
  import { useUserStore } from '@/store/modules/user'
  import { Cloud } from 'laf-client-sdk'
  import { ElMessage } from 'element-plus'
  import Error from '@/views/error/404.vue'
  import watermark from '@/utils/watermark.js'
  import { getSettingList } from '@/lafSdkCollection/getSettingInfo'
  const APPID = 'su75ks' // Laf 应用 appid
  const cloud = new Cloud({
    baseUrl: `https://${APPID}.laf.run`,
    getAccessToken: () => userStore.token,
  })
  const messageVisible = ref(false)
  const period = ref('')
  const name = ref('')
  const userStore = useUserStore()
  const Visible = ref(false)
  const cur_id = ref('')
  const total = ref(0)
  const status = ref(0)
  const currentPage = ref(1)
  const tableData = ref([])
  const tableDataCopy = ref([])
  const editorContent = ref('') //富文本编辑器内容，就是一段html代码
  const settingPeriod = ref()
  const message = ref('')
  const showMessage = (_id) => {
    messageVisible.value = true
    cur_id.value = _id
    message.value = tableData.value.find((item) => item._id == _id).content
  }
  const getSetting = async () => {
    const { period } = await getSettingList()
    settingPeriod.value = period
  }
  //获取当前页数
  const handelCurrentChange = async (nowPage) => {
    //获取当前页码
    currentPage.value = nowPage
    const res = await getApplyInfo(nowPage, 10, userStore._id)
    tableData.value = res.data
  }
  const searchByPeriod = () => {
    if (period.value.length > 0) {
      tableData.value = tableDataCopy.value
      tableData.value = tableData.value.filter((item) => item.name.match(period.value))
    } else {
      tableData.value = tableDataCopy.value
    }
  }
  const searchByName = () => {
    if (name.value.length > 0) {
      tableData.value = tableDataCopy.value
      tableData.value = tableData.value.filter((item) => item.personName.match(name.value))
    } else {
      tableData.value = tableDataCopy.value
    }
  }
  const failCheck = (_id) => {
    status.value = 3
    Visible.value = true
    cur_id.value = _id
  }

  const send = async () => {
    const data = {
      _id: cur_id.value,
      status: status.value,
      verify_message: editorContent.value,
    }
    const res = await cloud.invoke('changeApprovalStatus', data)
    tableData.value = []
    tableDataCopy.value = []
    if (res.code == 200) {
      ElMessage(res.message)
      Visible.value = false
    } else if (res.code == 400) {
      ElMessage(res.error)
    }
    getMessage()
  }
  const download = async (_id) => {
    const fileUrl = await cloud.invoke('getDocumentApproval', { _id })
    const link = document.createElement('a')
    link.href = fileUrl
    const n = tableData.value.find((item) => item._id === _id).personName
    const p = tableData.value.find((item) => item._id === _id).name
    const fileName = n + p + '审核文件.docx'
    link.download = fileName // 替换为你要保存的文件名
    link.target = '_blank'
    link.rel = 'noopener noreferrer'
    link.click()
  }
  const check = (_id) => {
    status.value = 2
    Visible.value = true
    cur_id.value = _id
  }
  const setWaterMark = () => {
    //添加水印
    watermark.set(userStore.info.branch_name, userStore.num)
    //移除水印,传 null 移除水印
    //watermark.close()
  }
  onUnmounted(async () => {
    watermark.close(null)
  })
  onMounted(async () => {
    setWaterMark()
    await getSetting()
    await getMessage()
  })
  const getStatus = (status) => {
    if (status == 1) {
      return '审核中'
    } else if (status == 2) {
      return '审核通过'
    } else if (status == 3) {
      return '审核不通过'
    }
  }
  const getMessage = async () => {
    const { res, count } = await getApproval(userStore._id)
    for (let i = 0; i < count.total; i++) {
      let baseTime = res.data[i].upload_date
      let d = new Date(baseTime)
      let batchDate = d.getFullYear() + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日'
      let Name = await getMemberName(res.data[i].person_id)
      let real = ''
      if (Name.data.length == 0) {
        real = '邹新榆(假数据)'
      } else {
        real = Name.data[0].name
      }
      tableData.value.push({
        _id: res.data[i]._id,
        personName: real,
        name: settingPeriod.value[parseInt(res.data[i].name)],
        content: res.data[i].content,
        upload_date: batchDate,
        key: res.data[i].key,
        status: getStatus(res.data[i].status),
      })
    }
    tableDataCopy.value = tableData.value
  }
</script>
<style scoped lang="scss">
  @import './index';
  .dialog-footer button:first-child {
    margin-right: 10px;
  }
</style>
